package com.qcby.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qcby.dao.ShopDao;
import com.qcby.entity.*;
import com.qcby.entity.Query.ShopQuery;
import com.qcby.service.ShopService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ShopServiceImpl implements ShopService {
    @Autowired
    private ShopDao shopDao;

    @Override
    public List<ShopSTag> findTag() {
        return shopDao.findTag();
    }

    @Override
    public PageResult<Shop> list(ShopQuery shopQuery) {
        PageHelper.startPage(shopQuery.getPage(), shopQuery.getPageSize());
        List<Shop> page1 =  shopDao.list(shopQuery);
        System.out.println(page1);
        Page<Shop> page2 = (Page<Shop>) page1;
        PageResult<Shop> pageResult = new PageResult<>(page2.getTotal(),page2.getResult());
        return pageResult;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void deleteById(Integer id) {
        shopDao.deleteById(id);
        shopDao.deleteTagId(id);
    }

    @Override
    public Shop findById(Integer id) {
        Shop shop = shopDao.findById(id);
        return shop;
    }
    @Override
    public List<ShopQuery> findAll(Shop shop) {
        return shopDao.findAll(shop);
    }
    @Override
    public List<Tag> findTags() {
        return shopDao.findTags();
    }
    @Override
    public List<Shop> selectShopByTag(String tagName) {
        return shopDao.selectShopByTag(tagName);
    }

    @Override
    public Shop goToDetail(Integer id) {
        return shopDao.goToDetail(id);
    }
    @Override
    public Result<Integer> like(Integer targetId, Integer userId) {
        if (targetId == null || userId == null) {
            return Result.error("用户ID或店铺ID为空，无法点赞");
        }
        int rows = shopDao.like(targetId, userId);
        return rows > 0 ? Result.success(rows) : Result.error("点赞失败");
    }

    @Override
    public Result<Integer> likeStatus(Integer targetId, Integer userId) {
        return Result.success(shopDao.likeStatus(targetId, userId));
    }

    @Override
    public Result<Integer> likeCount(@Param("targetId") Integer targetId, @Param("target_type")String target_type) {
        return Result.success(shopDao.likeCount(targetId,target_type));
    }

    @Override
    public Result<Integer> likeDelete(@Param("targetId") Integer targetId,
                                      @Param("userId") Integer userId,
                                      @Param("target_type")String target_type) {
        return Result.success(shopDao.likeDelete(targetId, userId,target_type));
    }

    @Override
    public List<User> findUserList() {
        return shopDao.findUserList();
    }

    @Override
    public void add(Shop shop) {
        shopDao.add(shop);
    }

    @Override
    public void updateById(Shop shop) {
        shopDao.updateById(shop);
    }

    @Override
    public Result<Integer> rating(Integer shopId, Integer userId, Integer rating) {
        return Result.success(shopDao.rating(shopId, userId,rating));
    }

    @Override
    public Result<Integer> ratingCount(@Param("shopId") Integer shopId,@Param("userId") Integer userId) {
        System.out.println("shopDao.ratingCount(shopId,userId)");
         System.out.println(shopDao.ratingCount(shopId,userId));
        return Result.success(shopDao.ratingCount(shopId,userId));
    }

    @Override
    public Result<Double> getRecent100RatingsAverage(Integer shopId) {
        return Result.success(shopDao.getRecent100RatingsAverage(shopId));
    }

    @Override
    public Result<Integer> updateShopRatingStatus() {
        return Result.success(shopDao.updateShopRatingStatus());
    }

    @Override
    public Result<Integer> addReview(Review review) {
        return Result.success(shopDao.addReview(review));
    }


    @Override
    public List<Shop> findAll1() {
        return shopDao.findAll1();
    }

    @Override
    public Result<List<Review>> getReplies(Integer reviewId) {
        return Result.success(shopDao.getReplies(reviewId));
    }

    @Override
    public Result<Integer> likeReview(@Param("targetId") Integer targetId,
                                      @Param("userId") Integer userId) {
        return Result.success(shopDao.likeReview(targetId,userId));
    }

    @Override
    public Result<Integer> syncReviewLikeCount(Integer count) {
        return Result.success(shopDao.syncReviewLikeCount());
    }

    @Override
    public Integer cancelReviewLike(@Param("targetId") Integer targetId,
                                    @Param("userId") Integer userId,
                                    @Param("target_type")String target_type) {
        return shopDao.cancelReviewLike(targetId, userId,target_type);
    }

    @Override
    public List<Shop> findByPage(ShopQuery query, int start, int pageSize) {
        // 1. 处理空参数（避免前端未传参导致的SQL错误）
        if (query.getName() != null && query.getName().trim().isEmpty()) {
            query.setName(null);
        }
        if (query.getTagName() != null && query.getTagName().trim().isEmpty()) {
            query.setTagName(null);
        }
        // 2. 调用Dao层查询当前页数据
        return shopDao.findByPage(query, start, pageSize);
    }

    @Override
    public int countByQuery(ShopQuery query) {
        // 与findByPage保持一致的空参数处理
        if (query.getName() != null && query.getName().trim().isEmpty()) {
            query.setName(null);
        }
        if (query.getTagName() != null && query.getTagName().trim().isEmpty()) {
            query.setTagName(null);
        }
        // 调用Dao层查询总条数
        return shopDao.countByQuery(query);
    }

/*    @Override
    public List<Review> getReviewsByShopId(Integer id) {
        return shopDao.getReviewsByShopId(id);
    }*/

    // ShopServiceImpl.java
    @Override
    public PageResult<Review> getShopReviews(Integer shopId, Integer page, Integer pageSize) {
        // 计算起始索引（start = (page-1)*pageSize）
        int start = (page - 1) * pageSize;
        // 调用 Dao 方法时，传递 shopId、start、pageSize（与 Mapper 接口参数对应）
        List<Review> reviews = shopDao.getReviewsByShopId(shopId, start, pageSize);
        // 查询总条数
        long total = shopDao.countReviewsByShopId(shopId);
        return new PageResult<>(total, reviews);
    }

    @Override
    public List<Shop> getShopsByUserId(Integer userId) {
        return shopDao.getShopsByUserId(userId);
    }
    @Override
    public List<Shop> getShopsByUserName(String userName) {
        return shopDao.getShopsByUserName(userName);
    }

    @Override
    public Shop getShopsByAduit(Integer id) {
        return shopDao.getShopsByAduit(id);
    }
}
